package com.example.dingdong.rest;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.dingdong.daomain.BasicUserEntity;
import com.example.dingdong.daomain.RoleEntity;
import com.example.dingdong.daomain.RouterEntity;
import com.example.dingdong.service.RoleService;
import com.example.dingdong.service.RouterService;
import com.example.dingdong.util.CheckRequestUtil;
import com.example.dingdong.util.ExceptionType;
import com.example.dingdong.util.MyException;



/**
 * 
 * @ClassName: RoleRest
 * @Description: 
 * @Author chengwenixng
 * @DateTime 2021-4-1 22:21
 */
@RestController
@RequestMapping("/web/rest/role/")
public class RoleRest {

	private static final Logger log = LoggerFactory.getLogger(RoleRest.class);

	@Autowired
	private RoleService roleService;

	@Autowired
	private RouterService routerService;

	/**
	 * 添加角色
	 */
	@PostMapping(value = "addRole", consumes = "application/json")
	public JSONObject addRole(@RequestBody String reqStr) {
		log.info("addRole 添加角色" + reqStr);

		/*
		 * 预返回数据
		 */
		JSONObject returnData = new JSONObject();
		JSONObject response = new JSONObject();
		returnData.put("cmd", "addRole");
		returnData.put("type", "response");
		returnData.put("response", response);

		try {
			JSONObject request = CheckRequestUtil.checkReqInterface(reqStr, "addRole");

			// 1、获取所有传入的数据
			String roleName = request.getString("roleName");
			String remark = request.getString("remark");

			// 2、校验前端数据
			if (StringUtils.isEmpty(roleName)) {
				throw new MyException(ExceptionType.NotFoundField, "请传入角色名！");
			}
			if (StringUtils.isEmpty(remark)) {
				throw new MyException(ExceptionType.NotFoundField, "请填写角色备注");
			}

			// 3、创建角色对象
			RoleEntity role = new RoleEntity(roleName, remark);
			roleService.saveRole(role);

			// 4、返回前端数据
			response.put("res", true);
		} catch (MyException e) {
			log.error("addRouter:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("addRouter:");
			log.error("error", e);
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		log.info("addRouter 接口方法调用完成");
		return returnData;
	}

	/**
	 * 删除角色
	 */
	@PostMapping(value = "deleteRole", consumes = "application/json")
	public JSONObject deleteRole(@RequestBody String reqStr) {
		log.info("deleteRole 删除角色:" + reqStr);

		/**
		 * 预返回数据
		 */
		JSONObject returnData = new JSONObject();
		JSONObject response = new JSONObject();
		returnData.put("cmd", "deleteRole");
		returnData.put("type", "response");
		returnData.put("response", response);

		try {

			JSONObject request = CheckRequestUtil.checkReqInterface(reqStr, "deleteRole");

			// 1、获取所有传入数据
			Integer id = request.getInteger("id");

			// 2、校验前端数据
			if (StringUtils.isEmpty(id)) {
				throw new MyException(ExceptionType.NotFoundField, "请填写角色信息!");
			}

			// 3、查找角色
			RoleEntity role = roleService.getRole(id, true);
			if (role == null) {
				throw new MyException(ExceptionType.OperationError, "角色无法删除！!");
			}

			/*
			 * 校验角色是否绑定了账号
			 */
			List<BasicUserEntity> basicDataList = role.getJoinBasicUserList();
			for (int i = 0; i < basicDataList.size(); i++) {
				BasicUserEntity basicData = basicDataList.get(i);
				if (basicData != null && basicData.isDelFlag()) {
					throw new MyException(ExceptionType.OperationError, "绑定了账号，角色无法删除");
				}
			}

			/*
			 * 校验角色是否绑定了路由
			 */
			List<RouterEntity> routerList = role.getRouterList();
			for (int i = 0; i < routerList.size(); i++) {
				RouterEntity router = routerList.get(i);
				if (router != null && router.isDelFlag()) {
					throw new MyException(ExceptionType.OperationError, "绑定了路由，角色无法删除");
				}
			}

			// 4、删除角色
			roleService.delRole(role);

			/**
			 * 返回前端数据
			 */
			response.put("res", true);
		} catch (MyException e) {
			log.error("deleteRole:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("deleteRole:");
			log.error("error", e);
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		log.info("deleteRole 接口方法调用完成");
		return returnData;
	}

	/**
	 * 查询角色
	 */
	@PostMapping(value = "findRole", consumes = "application/json")
	public JSONObject findRole(@RequestBody String reqStr) {
		log.info("findRole 查询角色:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject returnData = new JSONObject();
		JSONObject response = new JSONObject();
		returnData.put("cmd", "findRole");
		returnData.put("type", "response");
		returnData.put("response", response);

		try {
			CheckRequestUtil.checkReqInterface(reqStr, "findRole");

			// 1、查询所有角色
			List<RoleEntity> roleList = roleService.getRole();

			// 2、查找角色
			JSONArray message = new JSONArray();
			for (int i = 0; i < roleList.size(); i++) {
				RoleEntity role = roleList.get(i);
				JSONObject json = (JSONObject) JSONObject.toJSON(role);
				json.put("key", role.getId());
				message.add(json);
			}

			/**
			 * 返回前端数据
			 */
			response.put("res", true);
			response.put("message", message);
		} catch (MyException e) {
			log.error("findRole:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("findRole:");
			log.error("error", e);
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		log.info("findRole 接口方法调用完成");
		return returnData;
	}

	/**
	 * 修改角色信息
	 */
	@PostMapping(value = "editRole", consumes = "application/json")
	public JSONObject editRole(@RequestBody String reqStr) {
		log.info("editRole 修改角色信息" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject returnData = new JSONObject();
		JSONObject response = new JSONObject();
		returnData.put("cmd", "editRole");
		returnData.put("type", "response");
		returnData.put("response", response);

		try {
			JSONObject request = CheckRequestUtil.checkReqInterface(reqStr, "editRole");

			// 1、获取所有传入数据
			Integer id = request.getInteger("id");
			String roleName = request.getString("roleName");
			String remark = request.getString("remark");

			// 2、校验前端数据
			if (StringUtils.isEmpty(id)) {
				throw new MyException(ExceptionType.NotFoundField, "请传入角色!");
			}
			if (StringUtils.isEmpty(roleName)) {
				throw new MyException(ExceptionType.NotFoundField, "请传入角色名!");
			}
			if (StringUtils.isEmpty(remark)) {
				throw new MyException(ExceptionType.NotFoundField, "请传入角色备注");
			}

			// 3、查找角色对象
			RoleEntity role = roleService.getRole(id, true);
			if (role == null) {
				throw new MyException(ExceptionType.LookupDatabaseIsEmpty, "查询角色失败!");
			}
			// 4、更新角色数据
			roleService.updateRole(id, roleName, remark);

			/**
			 * 返回前端数据
			 */
			response.put("res", true);
		} catch (MyException e) {
			log.error("editRole:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("editRole:");
			log.error("error", e);
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		log.info("editRole接口方法调用完成");
		return returnData;
	}

	/**
	 * 根据角色查找路由数组
	 */
	@PostMapping(value = "getBindRouter", consumes = "application/json")
	public JSONObject getBindRouter(@RequestBody String reqStr) {
		log.info("getBindRouter 查找路由: " + reqStr);

		/*
		 * 预返回数据
		 */
		JSONObject returnData = new JSONObject();
		JSONObject response = new JSONObject();
		returnData.put("cmd", "getBindRouter");
		returnData.put("type", "response");
		returnData.put("response", response);

		try {
			JSONObject request = CheckRequestUtil.checkReqInterface(reqStr, "getBindRouter");
			// 获取传入的数据
			Integer id = request.getInteger("id");

			// 校验前端数据
			if (StringUtils.isEmpty(id)) {
				throw new MyException(ExceptionType.NotFoundField, "请传入id");
			}

			// 根据ID获取到这个角色
			RoleEntity role = roleService.getRole(id, true);
			if (role == null) {
				throw new MyException(ExceptionType.NotFoundField, "角色不存在");
			}

			List<String> routerIds = new ArrayList<>();
			role.getRouterList().forEach(router -> {
				if (router.isDelFlag() == true) {
					routerIds.add(router.getId() + "");
				}
			});

			response.put("res", true);
			response.put("message", routerIds);
		} catch (MyException e) {
			log.error("getBindRouter:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("getBindRouter:");
			log.error("error", e);
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		log.info("getBindRouter 接口方法调用完成");
		return returnData;
	}

	/**
	 * 角色绑定路由
	 */
	@PostMapping(value = "bindRouters", consumes = "application/json")
	public JSONObject bindRouters(@RequestBody String reqStr) {
		log.info("bindRouter 角色绑定路由: " + reqStr);

		/*
		 * 预返回数据
		 */
		JSONObject returnData = new JSONObject();
		JSONObject response = new JSONObject();
		returnData.put("cmd", "bindRouters");
		returnData.put("type", "response");
		returnData.put("response", response);

		try {
			JSONObject request = CheckRequestUtil.checkReqInterface(reqStr, "bindRouters");

			// 获取传入的数据
			Integer id = request.getInteger("id");
			JSONArray routerIdArray = request.getJSONArray("routerList");
			List<Integer> routerIdList = JSONObject.parseArray(routerIdArray.toJSONString(), Integer.class);

			// 校验前端数据
			if (StringUtils.isEmpty(id)) {
				throw new MyException(ExceptionType.NotFound, "角色ID不存在！");
			}
			if (StringUtils.isEmpty(routerIdList)) {
				throw new MyException(ExceptionType.NotFound, "路由不存在！");
			}

			// 查询角色
			RoleEntity role = roleService.getRole(id, true);
			if (role == null) {
				throw new MyException(ExceptionType.NotFound, "没有此角色角色");
			}

			// 根据路由数组进行角色互绑,判断routerList是否为空数组
			List<RouterEntity> routerList = new ArrayList<>();
			// routerList如果不为空，则获取
			if (!routerIdList.isEmpty()) {
				routerList = routerService.getRouters(routerIdList, true);
			}

			roleService.updataBindRouter(role, routerList);

			response.put("res", true);
		} catch (MyException e) {
			log.error("bindRouters:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("bindRouters:");
			log.error("error", e);
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		log.info("bindRouters接口方法调用完成");
		return returnData;
	}
}

